package org.framework.edu.service.impl;

import io.jsonwebtoken.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.framework.edu.properties.JwtTokenProperties;
import org.framework.edu.service.TokenService;
import org.joda.time.DateTime;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import javax.annotation.Resource;

@Slf4j
@Data
public class TokenServiceImpl implements TokenService {

    private JwtTokenProperties jwtTokenProperties;
    //散列算法
    private SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

    //压缩算法
    private CompressionCodec compressionCodec=CompressionCodecs.GZIP;
    @Override
    public String createToken(String userId, String username) {
        String token= Jwts.builder()
                .setId(userId)
                .setSubject(username)
                .setExpiration(DateTime.now().plusDays(jwtTokenProperties.getExpire()).toDate())
                .signWith(signatureAlgorithm, jwtTokenProperties.getSecret())
                .compressWith(compressionCodec)
                .compact();
        log.info("token是:{}",token);
        return token;
    }

    @Override
    public boolean verifyToken(String token) {
        try {
            Jwts.parser()
                    .setSigningKey(jwtTokenProperties.getSecret())
                    .parseClaimsJws(token);
            return true;
        }catch (Exception err){
            return false;
        }
    }

    @Override
    public String refreshToken(String token) {
        //刷新token
        //应该先将数据解析出来 然后从新生成
        Jws<Claims> claimsJws = Jwts.parser()
                .setSigningKey(jwtTokenProperties.getSecret())
                .parseClaimsJws(token);
        String id = claimsJws.getBody().getId();
        String username = claimsJws.getBody().getSubject();
        return createToken(id,username);
    }

    @Override
    public Jws<Claims> parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(jwtTokenProperties.getSecret())
                    .parseClaimsJws(token);
        }catch (Exception err){
            log.error("解析token抛出了异常:{}",token);
            return null;
        }
    }
}
